package srv

import (
	"fmt"
	"net/http"
	"regexp"

	"github.com/gin-gonic/gin"
)

// Cors 跨域请求规则
type Cors struct {
	HostRegex     string `json:"host_regex,omitempty" yaml:"host_regex,omitempty"`
	AllowMethods  string `json:"access_control_allow_methods,omitempty" yaml:"access_control_allow_methods,omitempty"`
	AllowHeaders  string `json:"access_control_allow_headers,omitempty" yaml:"access_control_allow_headers,omitempty"`
	ExposeHeaders string `json:"access_control_expose_headers,omitempty" yaml:"access_control_expose_headers,omitempty"`
}

// CorsAllow 跨域允许
func CorsAllow(cors Cors) gin.HandlerFunc {
	allow := false
	var r *regexp.Regexp
	if cors.HostRegex == "*" {
		allow = true
	} else if cors.HostRegex != "" {
		r1, err := regexp.Compile(cors.HostRegex)
		if err != nil {
			panic(fmt.Sprintf("启动失败，参数 host_regex 设置格式错误:%v", err))
		}
		r = r1
	}

	return func(c *gin.Context) {
		method := c.Request.Method

		origin := c.Request.Header.Get("Origin")
		var headerKeys []string
		for k := range c.Request.Header {
			headerKeys = append(headerKeys, k)
		}

		if origin != "" {

			if allow || r.MatchString(origin) {

				//下面的都是乱添加的-_-~
				// c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
				c.Header("Access-Control-Allow-Origin", origin)
				c.Header("Access-Control-Allow-Credentials", "true")
				if method == "OPTIONS" {
					headerStr := fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", cors.AllowHeaders)
					c.Header("Access-Control-Allow-Headers", headerStr)
					c.Header("Access-Control-Allow-Methods", cors.AllowMethods)
					// c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
					// c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
					c.Header("Access-Control-Expose-Headers", cors.ExposeHeaders)
					c.Header("Access-Control-Max-Age", "172800")
				}
			}

			// c.Header("Access-Control-Max-Age", "172800")
			//c.Header("Access-Control-Allow-Credentials", "true")
			//c.Set("content-type", "application/json")
		}

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "Options Request!")
		}

		c.Next()
	}
}
